﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Configuration;
namespace WebApplication1
{
    public partial class GioHang : System.Web.UI.Page
    {
        sv_QuanLyNhaSach.AdapterClient service = new sv_QuanLyNhaSach.AdapterClient();
        string SoHD;
        string MaTKOL = "";
        //string tt;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Browser.Cookies)
            {
                if (Request.Cookies.Get("Login") != null)
                {
                    HttpCookie MyCookies = Request.Cookies["Login"];
                    if (MyCookies["UserName"] != null)
                    {
                        MaTKOL = LayMaTK(MyCookies["UserName"].ToString());
                    }
                }
                else if (Session["UserName"] != null)
                {
                    MaTKOL = LayMaTK(Session["UserName"].ToString());
                }
            }
            SoHD = Request.QueryString["SoHD"];
            //tt = Request.QueryString["TT"];
            if (MaTKOL != "")
            {

                if (!IsPostBack)
                {
                    if (SoHD != null)
                    {
                        if (KT_Quyen(MaTKOL, SoHD) == false)
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "redirectMe", "alert('Bạn không được phép xem giỏ hàng này.');location.href='../DanhSachGioHang.aspx';", true);
                        }
                        Label1.Visible = true;
                        Load_GioHangCu(SoHD);
                    }
                    else if (Session["GioHang"] != null)
                    {
                        Label1.Visible = true;
                        Load_GioHang();
                    }
                    else
                        Label1.Visible = false;
                }
            }
            else
                Response.Redirect("TrangChu.aspx");
        }

        private bool KT_Quyen(string matk, string madh)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(service.selectqueryByText("select matkol,madhol from dathangonline where madhol='" + madh + "' and matkol ='" + matk + "'")));
            if (ds.Tables.Count > 0)
            {
                return true;
            }
            return false;
        }
        private string LayMaTK(string p)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(service.selectqueryByText("select matkol from TaiKhoanOnline where TenDangNhap='" + p + "' ")));
            if (ds.Tables.Count > 0)
            {
                return ds.Tables[0].Rows[0][0].ToString();
            }
            return "";
        }
        private void Load_GioHangCu(string SoHD)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(service.selectqueryByText("select c.mamh,tenmh,dongia,soluong,thanhtien,c.khuyenmai from CTDatHangONL c,mathang m where c.mamh=m.mamh and madhol='" + SoHD + "'")));
            if (ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ds.Tables[0].Rows[i]["dongia"] = ds.Tables[0].Rows[i]["dongia"].ToString().Replace(".0000", "");
                }
            }
            if (ds.Tables.Count > 0)
            {
                double tongthanhtien = 0;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    tongthanhtien += double.Parse(ds.Tables[0].Rows[i]["ThanhTien"].ToString());
                }
                lb_tongtien.Text = tongthanhtien.ToString("#,##0 VNĐ");
                Session["GioHangCu"] = ds.Tables[0];
                dl_sachmoi.DataSource = ds.Tables[0];
                dl_sachmoi.DataBind();
                //}
                //if (tt=="true")
                //{
                //    dl_sachmoi.FindControl("Button1").EnableTheming = false;
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {

        }
        protected void dl_sachmoi_ItemCommand(object source, DataListCommandEventArgs e)
        {
            TextBox txt_soluong;
            if (e.CommandName == "Sua")
            {
                if (MaTKOL == LayMaTK(Session["UserName"].ToString()))
                {
                    if (Session["GioHang"] != null && SoHD == null)
                    {
                        #region "gio hang moi"
                        DataTable tbl = (DataTable)Session["GioHang"];

                        txt_soluong = (TextBox)e.Item.FindControl("TextBox2");
                        for (int i = 0; i < tbl.Rows.Count; i++)
                        {
                            if (tbl.Rows[i]["MaMH"].ToString() == e.CommandArgument.ToString())
                            {
                                tbl.Rows[i]["SoLuong"] = int.Parse(txt_soluong.Text);
                            }
                        }
                        double tongthanhtien = 0;
                        for (int i = 0; i < tbl.Rows.Count; i++)
                        {
                            tongthanhtien += double.Parse(tbl.Rows[i]["ThanhTien"].ToString());
                        }
                        lb_tongtien.Text = tongthanhtien.ToString("#,##0 VNĐ");
                        Session["GioHang"] = tbl;
                        dl_sachmoi.DataSource = tbl;
                        dl_sachmoi.DataBind();

                        #endregion
                    }
                    else if (Session["GioHangCu"] != null && SoHD != null)
                    {
                        #region "gio hang cu"
                        DataTable tbl = (DataTable)Session["GioHangCu"];
                        txt_soluong = (TextBox)e.Item.FindControl("TextBox2");
                        for (int i = 0; i < tbl.Rows.Count; i++)
                        {
                            if (tbl.Rows[i]["MaMH"].ToString() == e.CommandArgument.ToString())
                            {
                                tbl.Rows[i]["Soluong"] = int.Parse(txt_soluong.Text).ToString("#,##0");
                                tbl.Rows[i]["ThanhTien"] = (double.Parse(txt_soluong.Text) * double.Parse(tbl.Rows[i]["DonGia"].ToString())).ToString("#,##0");
                            }
                        }
                        double tongthanhtien = 0;
                        for (int i = 0; i < tbl.Rows.Count; i++)
                        {
                            tongthanhtien += double.Parse(tbl.Rows[i]["ThanhTien"].ToString());
                        }
                        lb_tongtien.Text = tongthanhtien.ToString("#,##0 VNĐ");
                        Session["GioHangCu"] = tbl;
                        dl_sachmoi.DataSource = tbl;
                        dl_sachmoi.DataBind();
                        #endregion
                    }
                    else
                        Response.Redirect("TrangChu.aspx");
                }
            }
            else if (e.CommandName == "Xoa")
            {
                if (MaTKOL == LayMaTK(Session["UserName"].ToString()))
                {
                    if (Session["GioHang"] != null && SoHD == null)
                    {
                        double tongthanhtien = 0;
                        DataTable tbl = (DataTable)Session["GioHang"];
                        for (int i = 0; i < tbl.Rows.Count; i++)
                        {
                            if (tbl.Rows[i]["MaMH"].ToString() == e.CommandArgument.ToString())
                            {
                                tbl.Rows[i]["SoLuong"] = 0;
                            }
                        }
                        for (int i = 0; i < tbl.Rows.Count; i++)
                        {
                            tongthanhtien += double.Parse(tbl.Rows[i]["ThanhTien"].ToString());
                        }
                        Session["GioHang"] = tbl;
                        dl_sachmoi.DataSource = tbl;
                        dl_sachmoi.DataBind();
                        lb_tongtien.Text = tongthanhtien.ToString("#,##0 VNĐ");
                    }
                    else if (Session["GioHangCu"] != null && SoHD != null)
                    {
                        DataTable tbl = (DataTable)Session["GioHangCu"];
                        for (int i = 0; i < tbl.Rows.Count; i++)
                        {
                            if (tbl.Rows[i]["MaMH"].ToString() == e.CommandArgument.ToString())
                            {
                                tbl.Rows[i]["SoLuong"] = 0;
                            }
                        }
                        double tongthanhtien = 0;
                        for (int i = 0; i < tbl.Rows.Count; i++)
                        {
                            tongthanhtien += (double.Parse(tbl.Rows[i]["DonGia"].ToString())*int.Parse(tbl.Rows[i]["SoLuong"].ToString()));
                        }
                        lb_tongtien.Text = tongthanhtien.ToString("#,##0 VNĐ");
                        Session["GioHangCu"] = tbl;
                        dl_sachmoi.DataSource = tbl;
                        dl_sachmoi.DataBind();
                    }
                    else
                        Response.Redirect("TrangChu.aspx");
                }
            }
            else if (e.CommandName == "submit")
            {
                if (MaTKOL == LayMaTK(Session["UserName"].ToString()))
                {
                    if (Session["GioHang"] != null && SoHD == null)
                    {
                        #region "gio hang moi"
                        DataTable table = (DataTable)Session["GioHang"];
                        string dhol = matutang();
                        string hinhthuc = "Tiền mặt";
                        string trangthai = "CXN";
                        double tongthanhtien = 0;
                        DateTime ngaydathang = DateTime.Now;
                        if (MaTKOL != "")
                        {
                            for (int i = 0; i < table.Rows.Count; i++)
                            {
                                tongthanhtien += double.Parse(table.Rows[i]["ThanhTien"].ToString());
                            }
                            if (service.InsertDHOL(dhol, MaTKOL, ngaydathang, hinhthuc, trangthai, tongthanhtien))
                            {
                                for (int i = 0; i < table.Rows.Count; i++)
                                {
                                    if (table.Rows[i]["SoLuong"].ToString() != "0")
                                        service.InsertCTDHOL(dhol, table.Rows[i]["MaMH"].ToString(), int.Parse(table.Rows[i]["SoLuong"].ToString()), double.Parse(table.Rows[i]["DonGia"].ToString()), float.Parse(table.Rows[i]["KhuyenMai"].ToString()), double.Parse(table.Rows[i]["ThanhTien"].ToString()));
                                    //if (i == table.Rows.Count - 1)
                                    //{
                                    //    ScriptManager.RegisterStartupScript(this, this.GetType(), "redirectMe", "alert('Đặt hàng thành công.');location.href='../GioHang.aspx';", true);
                                    //}
                                }
                            }
                            Session["GioHang"] = null;
                            dl_sachmoi.DataSource = null;
                            dl_sachmoi.DataBind();
                            Response.Redirect("TrangTongTien.aspx?SoHD=" + dhol);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "redirectMe", "alert('Bạn chưa đăng nhập.');location.href='../GioHang.aspx';", true);
                        }
                        #endregion
                    }
                    else if (Session["GioHangCu"] != null && SoHD != null)
                    {
                        if (MaTKOL != "")
                        {
                            if (XetTrangThai(SoHD) == true)
                            {

                                #region "gio hang cu"
                                DataTable table = (DataTable)Session["GioHangCu"];
                                double tongthanhtien = 0;
                                for (int i = 0; i < table.Rows.Count; i++)
                                {
                                    tongthanhtien += double.Parse(table.Rows[i]["ThanhTien"].ToString());
                                }
                                service.selectqueryByText("update dathangonline set tongtien=" + tongthanhtien + " where madhol='" + SoHD + "'");
                                for (int i = 0; i < table.Rows.Count; i++)
                                {
                                    if (table.Rows[i]["SoLuong"].ToString() == "0")
                                        service.DeleteCTDHOL(SoHD, table.Rows[i]["MaMH"].ToString());
                                    service.UpdateCTDHOL(SoHD, table.Rows[i]["MaMH"].ToString(), int.Parse(table.Rows[i]["Soluong"].ToString()), double.Parse(table.Rows[i]["DonGia"].ToString()), float.Parse(table.Rows[i]["KhuyenMai"].ToString()), double.Parse(table.Rows[i]["ThanhTien"].ToString()));
                                    //if (i == table.Rows.Count - 1)
                                    //{                                    
                                    //    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('Sửa giỏ hàng thành công.');location.href='../GioHang.aspx';", true);
                                    //}
                                }
                                Session["GioHangCu"] = null;
                                dl_sachmoi.DataSource = null;
                                dl_sachmoi.DataBind();
                                Response.Redirect("TrangTongTien.aspx?SoHD=" + SoHD + "");
                                #endregion
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "redirectMe", "alert('Bạn không thể sửa đơn đặt hàng đã giao.');location.href='../GioHang.aspx';", true);
                            }
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "redirectMe", "alert('Bạn chưa đăng nhập.');location.href='../GioHang.aspx';", true);
                        }
                    }

                }
                else
                    Response.Redirect("TrangChu.aspx");
            }

        }

        private void Load_GioHang()
        {
            DataTable table = (DataTable)Session["GioHang"];
            double tongthanhtien = 0;
            for (int i = 0; i < table.Rows.Count; i++)
            {
                tongthanhtien += double.Parse(table.Rows[i]["ThanhTien"].ToString());
            }
            lb_tongtien.Text = tongthanhtien.ToString("#,##0 VNĐ");
            dl_sachmoi.DataSource = table;
            dl_sachmoi.DataBind();
        }
        private bool XetTrangThai(string madhol)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(service.selectqueryByText("select trangthai from DatHangOnline where MaDHOL ='" + madhol + "'")));
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows[0][0].ToString() != "DG")
                    return true;
            }
            return false;
        }
        private string matutang()
        {
            DataSet ds_tam = new DataSet();
            string mamoi = "";
            string maTam = "DHO";

            ds_tam.ReadXml(new StringReader(service.selectqueryByText("select top 1 MaDHOL from DatHangOnline where MaDHOL like '%" + maTam + "%'order by MaDHOL desc")));
            if (ds_tam.Tables.Count == 0)
                mamoi = maTam + "0001";
            else
            {
                string matam = ds_tam.Tables[0].Rows[0][0].ToString();
                string kituso = matam.Substring(3, 4).ToString();
                int somoi = int.Parse(kituso) + 1;
                mamoi = maTam + somoi.ToString("0000");
            }
            return mamoi;
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            if (MaTKOL != "")
            {
                Response.Redirect("DanhSachGioHang.aspx");
                Session["GioHangCu"] = null;
            }

        }
    }
}